import User from '../models/user';
import md5 from 'md5';
import { v4 as uuidv4 } from 'uuid'
export enum userType {
  ADMIN = 'admin',
  EVERYMAN = 'everyman',
  AUTHOR = 'author',
}
type UserDetail = {
  name: string
  mobile: string
  loginId: string
  loginPwd: any
  userType: userType
}
export const userService = {
  //添加管理员
  addAdmin: async (loginId, loginPwd) => {
    const id = uuidv4().replace(/-/g, '');
    loginPwd = md5(loginPwd);
    const result = await User.create({ loginId, loginPwd, userType: 'admin', id })
    return result.toJSON();
  },
  //修改管理员密码和名称
  updateAdmin: async (id, { loginId, loginPwd }) => {
    loginPwd = md5(loginPwd);
    const result = await User.update({ loginId, loginPwd }, {
      where: id
    });
    return result;
  },
  addUser: async (userDetail: UserDetail) => {
    userDetail.loginPwd = md5(userDetail.loginPwd);
    const result = await User.create(userDetail)
    return result.toJSON();
  },
  deleteUser: async (userId: string) => {
    const result = await User.destroy({
      where: {
        id: userId
      }
    })
    return result;
  },
  updateUser: async (userDetail: object, userId: string) => {
    const result = await User.update(userDetail, {
      where: {
        id: userId
      }
    })
    return result;
  },
  getUserInfo: async (userId: string) => {
    const result = await User.findByPk(userId);
    return result?.toJSON();
  },
  getAllUser: async () => {
    const result = await User.findAll();
    return result;
  }
}